import storage from 'good-storage'

/**
 * 辅助函数
 */
function inertArray (arr: any, val: any, compare: (item: any) => boolean, maxLen: number) {
  const isInclude = arr.some(compare)
  if (isInclude) { // 数组中已经包含此元素乐
      return false
  } else { // 没包含，在数组开始添加
    arr.unshift(val)
  }
  // 元素超过限定值，在末尾处移除
  if (arr.length > maxLen) {
    arr.pop()
  }
}

function deleteItemInArray (arr: any, compare: (item: any) => boolean) {
  const index = arr.findIndex(compare)
  if (index !== -1) {
    arr.splice(index, 1)
  }
}

/**
 * 添加
*/
export const add = (item: any, key: string, compare: (item: any) => boolean, maxLen: number) => {
  const list = storage.get(key, [])
  inertArray(list, item, compare, maxLen)
  storage.set(key, list)
  return list
}

/**
 * 删除
*/
export const remove = (key: string, compare:(item: any) => boolean) => {
  const list = storage.get(key, [])
  deleteItemInArray(list, compare)
  storage.set(key, list)
  return list
}

export const load = (key: string) => {
  return storage.get(key, [])
}

// function inertArray (arr: any, val: any, compare: () => any, maxLen: number) {
//   const index = arr.findIndex(compare)
//   if (index === 0) {
//     return
//   }
//   if (index > 0) {
//     arr.splice(index, 1)
//   }
//   arr.unshift(val)
//   if (maxLen && arr.length > maxLen) {
//     arr.pop()
//   }
// }

// function deleteFromArray(arr: any, compare: () => any) {
//   const index = arr.findIndex(compare)
//   if (index > -1) {
//     arr.splice(index, 1)
//   }
// }

// export function save(item: any, key: any, compare: () => any, maxLen: number) {
//   const items = storage.get(key, [])
//   inertArray(items, item, compare, maxLen)
//   storage.set(key, items)
//   return items
// }

// export function remove(key, compare) {
//   const items = storage.get(key, [])
//   deleteFromArray(items, compare)
//   storage.set(key, items)
//   return items
// }

// export function load(key) {
//   return storage.get(key, [])
// }

// export function clear(key) {
//   storage.remove(key)
//   return []
// }

// export function saveAll(items, key) {
//   storage.set(key, items)
// }
